package com.party.pay.service.pay;

import com.google.common.collect.Lists;
import com.party.common.constant.Constant;
import com.party.common.utils.LangUtils;
import com.party.common.utils.StringUtils;
import com.party.common.utils.VerifyCodeUtils;
import com.party.core.exception.OrderException;
import com.party.core.model.YesNoStatus;
import com.party.core.model.activity.ActStatus;
import com.party.core.model.activity.Activity;
import com.party.core.model.counterfoil.CounterfoilType;
import com.party.core.model.goods.Goods;
import com.party.core.model.goods.GoodsCoupons;
import com.party.core.model.member.MemberAct;
import com.party.core.model.order.*;
import com.party.core.service.activity.IActivityService;
import com.party.core.service.goods.IGoodsCouponsService;
import com.party.core.service.goods.IGoodsService;
import com.party.core.service.member.IMemberActService;
import com.party.core.service.order.IOrderFormService;
import com.party.pay.model.query.AliPayQueryResponse;
import com.party.pay.model.query.TradeStatus;
import com.party.pay.model.query.WechatPayQueryResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 支付回调处理
 *
 * @author yy-pc
 *
 */
@Service
public class PayOrderBizService {

	@Autowired
	private IOrderFormService orderFormService;

	@Autowired
	private IGoodsCouponsService goodsCouponsService;

	@Autowired
	private IGoodsService goodsService;

	@Autowired
	private IMemberActService memberActService;

	@Autowired
	private IActivityService activityService;

	/**
	 * 免费商品或活动
	 *
	 * @param orderId
	 * @param from
	 * @param from
	 * @throws OrderException
	 */
	@Transactional
	public void freeOrder(String orderId, String from) throws OrderException {
		/************* 更改业务状态 *****************/
		OrderForm orderForm = orderFormService.get(orderId);
		orderForm.setIsPay(PaymentState.IS_PAY.getCode()); // 已付款
		orderForm.setStatus(OrderStatus.ORDER_STATUS_HAVE_PAID.getCode()); // 成功
		orderForm.setMerchantId(TradeStatus.FREE.getCode()); // 标识为0元订单
		orderFormService.update(orderForm);

		// 如果是活动支付成功，设置活动报名状态
		if (OrderType.ORDER_ACTIVITY.getCode().equals(orderForm.getType())) {
			MemberAct dbMemberAct = memberActService.findByOrderId(orderId);
			dbMemberAct.setCheckStatus(ActStatus.ACT_STATUS_PAID.getCode()); // 已支付，报名成功
			if (null != dbMemberAct.getCounterfoilType() && dbMemberAct.getCounterfoilType().equals(CounterfoilType.TYPE_FREE.getCode())) {
				dbMemberAct.setPayStatus(MemberAct.PAY_STATUS_YES);
			}
			// 从签到页面来，自动签到
            if (StringUtils.isNotEmpty(from) && "signin".equals(from)) {
            	dbMemberAct.setSignin(YesNoStatus.YES.getCode());
			}
			memberActService.update(dbMemberAct);
		}

		/************* 生成核销码 *****************/
		goodsCoupons(orderForm.getGoodsId(), orderForm.getMemberId(), orderForm.getGoodsId(), orderForm.getType());
	}

	/**
	 * 免费商品或活动
	 *
	 * @param orderId
	 * @param from
	 * @param from
	 * @throws OrderException
	 */
	@Transactional
	public void freeOrder2(Integer type, String from, String goodsId, String currentUserId, String counterfoilId) throws OrderException {
		String businessIdTwo = ""; // 活动报名或者玩法预定ID
		// 如果是活动支付成功，设置活动报名状态
		if (OrderType.ORDER_ACTIVITY.getCode().equals(type)
				|| OrderType.ORDER_COURSE.getCode().equals(type)) {
			MemberAct dbMemberAct = memberActService.getMyAct(currentUserId, goodsId);
			if (dbMemberAct != null) {
				dbMemberAct.setCheckStatus(ActStatus.ACT_STATUS_PAID.getCode()); // 已支付，报名成功
				if (null != dbMemberAct.getCounterfoilType() && dbMemberAct.getCounterfoilType().equals(CounterfoilType.TYPE_FREE.getCode())) {
					dbMemberAct.setPayStatus(MemberAct.PAY_STATUS_YES);
				}
				// 从签到页面来，自动签到
				if (StringUtils.isNotEmpty(from) && "signin".equals(from)) {
					dbMemberAct.setSignin(YesNoStatus.YES.getCode());
				}
				memberActService.update(dbMemberAct);

				businessIdTwo = dbMemberAct.getId();


				/************* 生成核销码 *****************/
				goodsCoupons(goodsId, currentUserId, businessIdTwo, type);
			}
		}
	}

	public void goodsCoupons(String goodsId, String currentUserId, String businessIdTwo, Integer type){
		GoodsCoupons t = new GoodsCoupons();
		t.setGoodsId(goodsId);
		t.setMemberId(currentUserId);
		t.setStatus(YesNoStatus.YES.getCode());
		List<GoodsCoupons> goodsCouponss = goodsCouponsService.list(t);
		if (goodsCouponss.size() == 0) {
			List<String> verifyCodeList = getVerifyCode(businessIdTwo, 1);
			for (String verifyCode : verifyCodeList) {
				GoodsCoupons goodsCoupons = new GoodsCoupons();
				goodsCoupons.setOrderId("");
				goodsCoupons.setMemberId(currentUserId);
				goodsCoupons.setGoodsId(goodsId);
				goodsCoupons.setVerifyCode(verifyCode);
				goodsCoupons.setIsSpending("0");
				goodsCoupons.setIsBookings("0");
				goodsCoupons.setType(type);
				goodsCoupons.setStatus(1);
				goodsCouponsService.insert(goodsCoupons);
			}
		}
	}

	/**
	 * 更新预定成功人数
	 *
	 * @param orderId
	 */
	@Transactional(readOnly = false)
	public void updateJoinNum(String orderId) {
		OrderForm orderForm = orderFormService.get(orderId);
		// 成功的订单
		List<OrderForm> orderForms = orderFormService.getOrder(orderForm.getGoodsId(), null, false);

		if (OrderType.ORDER_ACTIVITY.getCode().equals(orderForm.getType())
				|| OrderType.ORDER_COURSE.getCode().equals(orderForm.getType())) {
			// 更新活动报名成功人数
			Activity activity = activityService.get(orderForm.getGoodsId());
			activity.setJoinNum(orderForms.size());
			activityService.update(activity);
		} else if (OrderType.ORDER_NOMAL.getCode().equals(orderForm.getType()) || OrderType.ORDER_CUSTOMIZED.getCode().equals(orderForm.getType())) {
			// 更新商品预定成功人数
			Goods goods = goodsService.get(orderForm.getGoodsId());
			goods.setJoinNum(orderForms.size());
			goodsService.update(goods);
		}
	}

	/**
	 * 处理支付业务
	 *
	 * @param orderId
	 * @param from
	 * @throws Exception
	 */
	@Transactional(readOnly = false)
	public void updatePayBusiness(String orderId) throws Exception {
		freeOrder(orderId, null);
		// updateJoinNum(orderId);
	}

	/**
	 * 免费活动/商品处理业务
	 * @param type
	 * @param from
	 * @param goodsId
	 * @throws Exception
	 */
	@Transactional(readOnly = false)
	public void updatePayBusiness2(Integer type, String from, String goodsId, String memberId, String counterfoilId) throws Exception {
		freeOrder2(type, from, goodsId, memberId, counterfoilId);
	}

	/**
	 * 生成核销码
	 *
	 * @param orderFormId
	 *            订单号
	 * @param unit
	 *            订单份数
	 * @return 核销码列表
	 */
	public List<String> getVerifyCode(String orderFormId, Integer unit) {
		if (unit == 0) {
			throw new OrderException(10063, "生成核销码异常，订单数量为0");
		}

		List<String> verifyCodeList = Lists.newArrayList();
		for (int i = 0; i < unit; i++) {
			String verifyCode = VerifyCodeUtils.buildVerifyCode(orderFormId);
			if (StringUtils.isNotEmpty(verifyCode)) {
				verifyCodeList.add(verifyCode);
			}
		}
		return verifyCodeList;
	}
    /**
     * 检查订单状态，检查订单是否还能二次使用
     *
     * @param payment        金额
     * @param paymentWay     支付方式
     * @param responseObject 查询结果
     * @return
     */
    public boolean checkOrderStatus(Float payment, Integer paymentWay, Object responseObject) {
        boolean flag = false;
        if (responseObject != null) {
            if (paymentWay.equals(PaymentWay.WECHAT_PAY.getCode())) {
                WechatPayQueryResponse response = (WechatPayQueryResponse) responseObject;
                if (Constant.WECHAT_SUCCESS.equals(response.getReturnCode()) && Constant.WECHAT_SUCCESS.equals(response.getResultCode())) {
                    if (response.getTradeState().equals(TradeStatus.WX_NOTPAY.getCode()) || response.getTradeState().equals(TradeStatus.WX_REFUND.getCode())) {
                        flag = true;
                    }
                }
            } else if (paymentWay.equals(PaymentWay.ALI_PAY.getCode())) {
                AliPayQueryResponse response = (AliPayQueryResponse) responseObject;
                if (response.getCode().equals(Constant.ALI_SUCCESS_CODE)) {
                    if (StringUtils.isNotEmpty(response.getTotalAmount())) {
                        Float total = Float.valueOf(response.getTotalAmount());
                        if (!total.equals(payment)) {
                            flag = true;
                        }
                    }
                    if (StringUtils.isNotEmpty(response.getTradeStatus())) {
                        if (response.getTradeStatus().equals(TradeStatus.ALI_TRADE_SUCCESS.getCode())
                                || response.getTradeStatus().equals(TradeStatus.ALI_TRADE_CLOSED.getCode())
                                || response.getTradeStatus().equals(TradeStatus.ALI_TRADE_FINISHED.getCode())
                                || response.getTradeStatus().equals(TradeStatus.ALI_WAIT_BUYER_PAY.getCode())) {
                            flag = true;
                        }
                    }
                }
            }
        }
        return flag;
    }

    /**
     * 检查未支付状态
     *
     * @param paymentWay     支付方式
     * @param responseObject 响应结果
     * @return
     */
    public boolean checkNotPayTradeState(Integer paymentWay, Object responseObject) {
        if (responseObject != null) {
            if (paymentWay.equals(PaymentWay.WECHAT_PAY.getCode())) {
                WechatPayQueryResponse response = (WechatPayQueryResponse) responseObject;
                if (Constant.WECHAT_SUCCESS.equals(response.getReturnCode()) && Constant.WECHAT_SUCCESS.equals(response.getResultCode())) {
                    // 状态为已支付或已退款或正在支付中返回false，不能取消。
                    if (response.getTradeState().equals(TradeStatus.WX_SUCCESS.getCode())
                            || response.getTradeState().equals(TradeStatus.WX_REFUND.getCode())
                            || response.getTradeState().equals(TradeStatus.WX_USERPAYING.getCode())) {
                        return false;
                    }
                }
            } else if (paymentWay.equals(PaymentWay.ALI_PAY.getCode())) {
                AliPayQueryResponse response = (AliPayQueryResponse) responseObject;
                if (response.getCode().equals(Constant.ALI_SUCCESS_CODE)) {
                    // 状态为已支付或已完成返回false，不能取消。
                    if (response.getTradeStatus().equals(TradeStatus.ALI_TRADE_SUCCESS.getCode())
                            || response.getTradeStatus().equals(TradeStatus.ALI_TRADE_FINISHED.getCode())) {
                        return false;
                    }
                }
            }
        }
        return true;
    }

	/**
	 * @param orderForm 订单信息
	 * @return
	 * @Author yifeng
	 * @Description 获取订单的核销码
	 * @Date 14:52 2019/4/10
	 **/
	public List<String> getCouponsList(OrderForm orderForm) {
		List<GoodsCoupons> couponsList = goodsCouponsService.findByOrderId(orderForm.getId());
		if (couponsList.size() > 0) {
			List<String> verifyCodeList = LangUtils.transform(couponsList, input -> input.getVerifyCode());
			return verifyCodeList;
		} else {
			List<String> verifyCodeList = this.getVerifyCode(orderForm.getId(), orderForm.getUnit());
			for (String verifyCode : verifyCodeList) {
				GoodsCoupons goodsCoupons = new GoodsCoupons();
				goodsCoupons.setOrderId(orderForm.getId());
				goodsCoupons.setMemberId(orderForm.getMemberId());
				goodsCoupons.setGoodsId(orderForm.getGoodsId());
				goodsCoupons.setVerifyCode(verifyCode);
				goodsCoupons.setType(orderForm.getType());
				goodsCouponsService.insert(goodsCoupons);
			}
			return verifyCodeList;
		}
	}
}
